<template>
  <div class="order-management-container">
    <!-- 搜索筛选区 -->
    <div class="filter-card">
      <el-form :model="filterForm" inline>
        <!-- 基础信息 -->
        <el-form-item label="订单ID">
          <el-input v-model.number="filterForm.oid" placeholder="订单ID" clearable @keyup.enter="handleSearch"
            style="width: 100px;" />
        </el-form-item>

        

        <el-form-item label="产品ID">
          <el-input v-model.number="filterForm.pid" placeholder="产品ID" clearable style="width: 70px;" />
        </el-form-item>

       

    
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="resetFilters" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <el-table :data="tableData" v-loading="loading" border stripe highlight-current-row style="width: 100%">
        <el-table-column prop="oid" label="订单ID" width="110" sortable align="center" />
        <el-table-column prop="cid" label="客户ID" width="100" sortable align="center" />
        <el-table-column prop="pid" label="产品ID" width="100" sortable align="center" />

        <el-table-column prop="price" label="单价(元)" width="80" align="right">
          <template #default="{ row }">
            {{ formatPrice(row.price) }}
          </template>
        </el-table-column>

        <el-table-column prop="quantity" label="数量" width="80" align="center" />

        <el-table-column prop="totalAmount" label="总价(元)" width="120" sortable align="right">
          <template #default="{ row }">
            {{ formatPrice(row.totalAmount) }}
          </template>
        </el-table-column>

        <el-table-column label="订单状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="orderDate" label="下单日期" width="120" sortable>
          <template #default="{ row }">
            {{ formatDate(row.orderDate) }}
          </template>
        </el-table-column>

        <el-table-column prop="eta" label="预计交付" width="120">
          <template #default="{ row }">
            {{ formatDate(row.eta) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)" :icon="Edit" type="primary">
              编辑
            </el-button>
            <el-button size="small" @click="handleDetail(row)" :icon="View" type="primary">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-section">
      <el-button 
        :disabled="!hasPrevPage || loading" 
        @click="loadPrevPage"
        v-if="hasPrevPage"
      >
        ← 上一页 
      </el-button>
      
      <el-button 
        :disabled="!hasNextPage || loading" 
        @click="loadNextPage"
        :loading="loading"
      >
        {{ loading ? '加载中...' : '下一页 →' }}
      </el-button>
 
      <span class="page-info" v-if="tableData.length  > 0">
        当前显示 {{ tableData.length  }} 条记录 
        <span v-if="!hasNextPage">- 已加载全部</span>
      </span>
    </div>

    
    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单信息" width="50%" @closed="resetEditForm">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="120px">
       
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="editForm.status">
            <el-option label="生产中" :value="1" />
            <el-option label="已送达" :value="2" />

          </el-select>
        </el-form-item>


      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">保存</el-button>
      </template>
    </el-dialog>
    <!-- 弹窗2 -->
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="订单详情" width="60%">
      <el-descriptions :column="2" border>
        <!-- 客户信息（始终显示） -->
        <el-descriptions-item label="客户昵称*">{{ detailData.customer?.name || '无' }}</el-descriptions-item>
        <el-descriptions-item label="客户公司">{{ detailData.customer?.company || '无' }}</el-descriptions-item>
        <el-descriptions-item label="客户电话">{{ detailData.customer?.phone || '无' }}</el-descriptions-item>

        <!-- 产品基本信息（始终显示） -->
        <el-descriptions-item label="产品名称*">{{ detailData.product?.name || '无' }}</el-descriptions-item>
        <el-descriptions-item label="产品价格">{{ formatPrice(detailData.product?.price) }}</el-descriptions-item>
        <el-descriptions-item label="叉型">
          {{ detailData.product?.sidefork === 1 ? '四面叉' : '二面叉' }}
        </el-descriptions-item>
        <el-descriptions-item label="板材类型">
          {{ detailData.product?.panel_Leg === 0 ? '板条-原木' : '胶合板-多层板' }}
        </el-descriptions-item>
        <el-descriptions-item label="定制类型">
          {{ detailData.product?.customize === 0 ? '二手' : '定制' }}
        </el-descriptions-item>

        <!-- 仅定制产品显示技术规格 -->
        <template v-if="detailData.product?.customize === 1">
          <!-- 二面叉专属内容 -->
          <template v-if="detailData.product?.sidefork === 0">
            <el-descriptions-item label="底部拉秤">
              {{ detailData.product?.t_bottomlayer === 0 ? '无' : '有' }}
            </el-descriptions-item>
            <el-descriptions-item label="腿布局">
              {{
                detailData.product?.t_leglayout === 0 ? '无' :
                detailData.product?.t_leglayout === 1 ? '三条腿' :
                  detailData.product?.t_leglayout === 2 ? '四条腿' : '未知'
              }}
            </el-descriptions-item>
          </template>

          <!-- 四面叉专属内容 -->
          <template v-else-if="detailData.product?.sidefork === 1">
            <el-descriptions-item label="结构类型">
              {{
                detailData.product?.f_structure === 'N' ? '无' :
                detailData.product?.f_structure === 'A' ? 'A型结构' : 'B型结构'
              }}
            </el-descriptions-item>
            <el-descriptions-item label="垫块高度">
              {{ detailData.product?.f_blockheight || 0 }} cm
            </el-descriptions-item>
          </template>

          <!-- 通用技术规格（无论哪种叉型都显示） -->
          <el-descriptions-item label="板翼">
            {{ detailData.product?.tf_boardwing || 0 }} cm
          </el-descriptions-item>
        </template>

        <!-- 备注（始终显示） -->
        <el-descriptions-item label="备注" :span="2">
          <el-input v-model="detailData.remark" type="textarea" :rows="2" readonly resize="none"
            :placeholder="detailData.remark ? '' : '无备注信息'" />
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>



  </div>
</template>
 
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Refresh, Edit,View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { 
  customer_ListWithFiltersAPI, 
  order_ListWitheFiltersAPI,
  product_ListWithFiltersAPI ,order_updateAPI
} from '@/api/api'
import authStore from '@/model/authstore'
 
const router = useRouter()
const authData = authStore.get('auth') ??{}
 
// 详情对话框相关 
const detailDialogVisible = ref(false)
const detailData = ref({
  oid: '',
  cid: '',
  pid: '',
  price: 0,
  quantity: 0,
  totalAmount: 0,
  status: 0,
  orderDate: '',
  eta: '',
  remark: '',
  customer: {
    company: '',
    name: '',
    phone: ''
  },
  product: {
    name: '',
    sidefork: 0,
    panel_Leg: 0,
    customize: 0,
    t_bottomlayer: 0,
    t_leglayout: 0,
    tf_boardwing: 0,
    f_structure: 'N',
    f_blockheight: 0,
    price: 0,
  }
})
 
// 组件状态 
const loading = ref(false)
const tableData = ref([])
const cursorStack = ref([null]) // 游标历史栈 
const hasNextPage = ref(true)   // 是否有下一页 
const hasPrevPage = ref(false)  // 是否有上一页 
const currentCursor = ref(null) // 当前游标（新增）
 
// 筛选表单 
const filterForm = reactive({
  oid: null,
  cid: authData.user?.cid ?? null, 
  pid: null,
  orderDateRange: [],
  etaRange: [],
  minPrice: null,
  maxPrice: null,
  status: 1 
})
 
// 初始化加载 
onMounted(() => {
  loadFirstPage()

})
 
// 构建请求参数 
const buildParams = (cursor = null) => {
  const params = {
    cursor: cursor,
    limit: 10,
    oid: filterForm.oid, 
    cid: authData.user.cid, 
    pid: filterForm.pid, 
    status: 1, 
    minPrice: filterForm.minPrice, 
    maxPrice: filterForm.maxPrice  
  }
 
  // 处理日期范围 
  if (filterForm.orderDateRange?.length  === 2) {
    params.startOrderDate  = filterForm.orderDateRange[0] 
    params.endOrderDate  = filterForm.orderDateRange[1] 
  }
 
  if (filterForm.etaRange?.length  === 2) {
    params.startEta  = filterForm.etaRange[0] 
    params.endEta  = filterForm.etaRange[1] 
  }
 
  return params 
}
 
// 加载第一页数据 
const loadFirstPage = async () => {
  cursorStack.value  = [null]
  currentCursor.value  = null 
  hasPrevPage.value  = false 
  await loadData(null)
}
 
// 核心数据加载方法（关键修改）
const loadData = async (cursor = null) => {
  loading.value  = true 
  try {
    const params = buildParams(cursor)
    const res = await order_ListWitheFiltersAPI(params)
 
    if (res.code  === 200) {
      tableData.value  = res.data.data  || []
      hasNextPage.value  = res.data.hasNext  
      currentCursor.value  = res.data.nextCursor  // 更新当前游标 
 
      // 更新游标栈（仅当是新页面时）
      if (cursor !== null && res.data.data?.length  > 0) {
        cursorStack.value.push(cursor) 
      }
 
      // 更新是否有上一页状态 
      hasPrevPage.value  = cursorStack.value.length  > 1 
 
      // console.log(' 分页状态:', {
      //   hasNext: hasNextPage.value, 
      //   currentCursor: currentCursor.value, 
      //   cursorStack: cursorStack.value  
      // })
    } else {
      ElMessage.error(res.message  || '获取数据失败')
    }
  } catch (error) {

    ElMessage.error(' 加载失败: ' + error.message) 
  } finally {
    loading.value  = false 
  }
}
 
// 加载下一页（关键修改）
const loadNextPage = async () => {
  if (!hasNextPage.value  || loading.value)  return 
  
  // 使用当前游标加载下一页 
  await loadData(currentCursor.value) 
}
 
// 加载上一页 
const loadPrevPage = async () => {
  if (cursorStack.value.length  <= 1 || loading.value)  return 
  
  // 回退到上一个游标 
  cursorStack.value.pop() 
  const prevCursor = cursorStack.value[cursorStack.value.length  - 1] || null 
  await loadData(prevCursor)
}
 
// 处理搜索 
const handleSearch = () => {
  loadFirstPage()
}
 
// 重置筛选条件 
const resetFilters = () => {
  Object.keys(filterForm).forEach(key  => {
    if (key === 'orderDateRange' || key === 'etaRange') {
      filterForm[key] = []
    } else {
      filterForm[key] = null 
    }
  })
  loadFirstPage()
}
 
// 查看订单详情 
const handleDetail = async (row) => {
  try {
    loading.value  = true 
    detailDialogVisible.value  = true 
 
    // 初始化详情数据 
    detailData.value  = {
      oid: row.oid, 
      cid: row.cid, 
      pid: row.pid, 
      price: row.price, 
      quantity: row.quantity, 
      totalAmount: row.totalAmount, 
      status: row.status, 
      orderDate: row.orderDate, 
      eta: row.eta, 
      remark: row.remark  || '',
      customer: { company: '', name: '', phone: '' },
      product: { ...detailData.value.product  }
    }
 
    // 并行获取客户和产品详情 
    const [customerRes, productRes] = await Promise.all([ 
      customer_ListWithFiltersAPI({ cid: row.cid,  limit: 1 }),
      product_ListWithFiltersAPI({ pid: row.pid,  limit: 1 })
    ])
    
    // 更新客户信息 
    if (customerRes.data?.data?.[0])  {
      detailData.value.customer  = {
        ...detailData.value.customer, 
        ...customerRes.data.data[0] 
      }
    }
 
    // 更新产品信息 
    if (productRes.data?.data?.[0])  {
      detailData.value.product  = {
        ...detailData.value.product, 
        ...productRes.data.data[0] 
      }
    }
 
  } catch (error) {

    ElMessage.error(` 获取详情失败: ${error.message}`) 
    detailDialogVisible.value  = false 
  } finally {
    loading.value  = false 
  }
}
 
// 辅助方法：格式化价格 
const formatPrice = (price) => {
  return price ? Number(price).toFixed(2) : '0.00'
}
 
// 辅助方法：格式化日期 
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr.split('T')[0] 
}
 
// 辅助方法：获取状态文本 
const getStatusText = (status) => {
  const statusMap = {
    0: '待激活',
    1: '生产中',
    2: '已送达',
    3: '已结算',
  }
  return statusMap[status] || '未知状态'
}
 
// 辅助方法：获取状态标签类型 
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'primary',
    3: 'info',
  }
  return typeMap[status] || ''
}


// 编辑对话框相关 
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  status: null,

})

// 编辑订单 
const handleEdit = (row) => {
  Object.assign(editForm, {
    status: row.status, 
  })
  editDialogVisible.value = true 
}

// 提交编辑表单 
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate() 

    const response = await order_updateAPI(editForm)

    if (response.code === 200) {
      ElMessage.success(response.message || '订单更新成功')
      editDialogVisible.value = false 

      // 更新本地数据 
      const index = tableData.value.findIndex(item => item.oid === editForm.oid) 
      if (index !== -1) {
        tableData.value[index] = { ...tableData.value[index], ...editForm }
      }
    } else {
      ElMessage.error(response?.message || '订单更新失败')
    }
  } catch (error) {

    ElMessage.error(error.message || '请求异常')
  }
}

</script>
 
<style scoped>
.order-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.filter-card {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-card {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 15px;
  margin-right: 15px;
}
</style>